package com.xindz.hgq.database.realm.view;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Button;

import com.blankj.utilcode.constant.TimeConstants;
import com.blankj.utilcode.util.TimeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.xindz.hgq.R;
import com.xindz.hgq.adapter.SimpleAdapter;
import com.xindz.hgq.base.BaseTitleActivity;
import com.xindz.hgq.base.options.BaseActivityOptions;
import com.xindz.hgq.database.realm.bean.User;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.realm.Realm;
import io.realm.RealmQuery;
import io.realm.RealmResults;

/**
 * @name HGQBase
 * @class name：com.xindz.hgq.database.realm.view
 * @describe describe
 * @anthor XINDZ
 * @time 2018/5/29 11:50
 * @change
 * @chang time
 * @class describe
 */
public class RealmSimpleExampleActivity extends BaseTitleActivity {
    @BindView(R.id.bt_realm_se_insert)
    Button btRealmSeInsert;
    @BindView(R.id.bt_realm_se_delete)
    Button btRealmSeDelete;
    @BindView(R.id.bt_realm_se_delete_all)
    Button btRealmSeDeleteAll;

    @BindView(R.id.bt_realm_se_query)
    Button btRealmSeQuery;
    @BindView(R.id.bt_realm_se_query_all)
    Button btRealmSeQueryAll;
    @BindView(R.id.rcv_realm_se)
    RecyclerView rcvRealmSe;
    private List<String> dataStringList;
    private SimpleAdapter adapter;
    private Realm realm;
    private int num = 0;

    @Override
    public BaseActivityOptions setOption() {
        return new BaseActivityOptions().openTitle();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (!realm.isClosed())
            realm.close();
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_realm_simply_example);
        ButterKnife.bind(this);
        rcvRealmSe.setLayoutManager(new LinearLayoutManager(this));
        dataStringList = new ArrayList<>();
        adapter = new SimpleAdapter(R.layout.item_gd_relation, dataStringList);
        rcvRealmSe.setAdapter(adapter);
        realm = Realm.getDefaultInstance();
    }

    @OnClick({R.id.bt_realm_se_insert, R.id.bt_realm_se_delete, R.id.bt_realm_se_delete_all,  R.id.bt_realm_se_query, R.id.bt_realm_se_query_all})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.bt_realm_se_insert:
                User user = createUser();
                realm.executeTransaction(new Realm.Transaction() {
                    @Override
                    public void execute(Realm realm) {
                        //所有写入必须封装在事务之中
                        realm.copyToRealmOrUpdate(user);
                    }
                });
                break;
            case R.id.bt_realm_se_delete:
                RealmResults<User> users = findAll();
                realm.executeTransaction(new Realm.Transaction() {
                    @Override
                    public void execute(Realm realm) {
                        boolean deleteResult = users.deleteFirstFromRealm();
                        if (deleteResult) {
                            ToastUtils.showShort("删除第一条数据成功");
                        } else {
                            ToastUtils.showShort("删除第一条数据失败");
                        }
                    }
                });

                break;
            case R.id.bt_realm_se_delete_all:
                realm.executeTransaction(new Realm.Transaction() {
                    @Override
                    public void execute(Realm realm) {
                        realm.delete(User.class);
                        ToastUtils.showShort("删除User数据成功");
                    }
                });

                break;

            case R.id.bt_realm_se_query:
                break;
            case R.id.bt_realm_se_query_all:
                findAll();
                break;
        }
    }

    private User createUser() {
        num++;
        long timeMillis = System.currentTimeMillis();
        String objId = timeMillis + "";
        Date dateByNow = TimeUtils.getDateByNow(timeMillis, TimeConstants.MSEC);
        return new User(objId, "小明" + num, 1, true, dateByNow);
    }

    private RealmResults<User> findAll() {
        dataStringList.clear();
        RealmQuery<User> userRealmQuery = realm.where(User.class);
        RealmResults<User> users = userRealmQuery.findAll();
        for (User user : users) {
            String sb = ("objecId  :   " + user.getObjecId() + "\n") +
                    "username   :   " + user.getUsername() + "\n" +
                    "sex   :   " + user.getSex() + "\n" +
                    "mobilePhoneVerified   :   " + user.getMobilePhoneVerified() + "\n" +
                    "createdAt   :   " + user.getCreatedAt().toString() + "\n";

            dataStringList.add(sb);
        }
        adapter.notifyDataSetChanged();
        ToastUtils.showShort("查询完成");
        return users;
    }
}
